import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getCookie, getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { Message } from 'element-ui'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  // console.log("tiaozhuanqian",to.path)
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // console.log("hasTOken",hasToken)
  setTimeout(async()=>{
    const hasToken = getToken();
    if (hasToken) {
      // 如果刷新之前路径是/404登陆后进入主页
      if (to.path == "/404") {
        next({ path: '/' })
      }
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done() 
      } else {
        // console.log("hasRoles")
        const hasRoles = store.getters.hasRoles && store.getters.hasRoles.length > 0
        // console.log("hasRoles",hasRoles);
        if (hasRoles) {
          //动态路由刷新后需要重新获取路由
            // console.log("refersh",store.state.permission.refreshStaus);
            if(store.getters.refreshStaus&&!store.getters.firstLogin){
              let roles = store.getters.hasRoles
              const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
              router.addRoutes(accessRoutes)
              next({...to,replace:true})
              store.state.permission.refreshStaus = false;
            }
            else{
              next();
            }
        }
        else {
          try {
            let roles = await store.dispatch('user/hasRoles')
            // generate accessible routes map based on roles
            // console.log(roles)
          
            const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
            router.addRoutes(accessRoutes)
            next({ ...to, replace: true })
          } catch (error) {
            // remove token and go to login page to re-login
            await store.dispatch('user/resetToken')
            Message.error(error || '请登录')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        }
      }
    } else {
      /* has no token*/
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  },800)
 

})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
